/**
 * 模块化图谱可视化中心
 * 
 * 基于插件系统的图谱可视化组件
 * 支持动态加载和组合不同的图谱类型和布局
 */

import React, { forwardRef, useImperativeHandle, useRef, useEffect, useState } from 'react';
import { message } from 'antd';
import pluginInitializer from '../../plugins/PluginInitializer';

const ModularGraphVisualizationHub = forwardRef(({ 
  nodes = [], 
  edges = [], 
  graphType = 'knowledge',
  layout = 'force', 
  onLayoutChange,
  onNodeClick,
  onEdgeClick,
  onNodePositionUpdate,
  editable = false,
  width = '100%',
  height = 500,
  zoom = 1,
  animationSpeed = 0.3,
  isSimulationRunning = true,
  isFullscreen = false,
  onToggleFullscreen,
  errorHandler = (error) => console.error("图谱渲染错误:", error)
}, ref) => {
  const componentRef = useRef(null);
  const [isPluginReady, setIsPluginReady] = useState(false);
  const [currentPlugin, setCurrentPlugin] = useState(null);
  const [error, setError] = useState(null);

  // 初始化插件系统
  useEffect(() => {
    const initializePlugins = async () => {
      try {
        await pluginInitializer.initialize();
        setIsPluginReady(true);
      } catch (error) {
        console.error('插件系统初始化失败:', error);
        setError(error);
        errorHandler(error);
      }
    };

    if (!pluginInitializer.isInitialized()) {
      initializePlugins();
    } else {
      setIsPluginReady(true);
    }
  }, [errorHandler]);

  // 获取并设置当前插件
  useEffect(() => {
    if (!isPluginReady) return;

    try {
      const registry = pluginInitializer.getRegistry();
      const plugin = registry.getCombinationPlugin(graphType, layout);
      
      if (!plugin) {
        const errorMsg = `未找到匹配的插件组合: ${graphType} + ${layout}`;
        console.warn(errorMsg);
        
        // 尝试使用默认组合
        const fallbackPlugin = registry.getCombinationPlugin('knowledge', 'force');
        if (fallbackPlugin) {
          setCurrentPlugin(fallbackPlugin);
          message.warning(`使用默认插件组合替代: knowledge + force`);
        } else {
          throw new Error('无法找到任何可用的插件组合');
        }
      } else {
        setCurrentPlugin(plugin);
      }
    } catch (error) {
      console.error('获取插件失败:', error);
      setError(error);
      errorHandler(error);
    }
  }, [isPluginReady, graphType, layout, errorHandler]);

  // 暴露方法给父组件
  useImperativeHandle(ref, () => ({
    // 居中图谱
    centerGraph: () => {
      if (componentRef.current && componentRef.current.centerGraph) {
        componentRef.current.centerGraph();
      }
    },
    
    // 开始动画
    startSimulation: (speed) => {
      if (componentRef.current && componentRef.current.startSimulation) {
        componentRef.current.startSimulation(speed);
      }
    },
    
    // 暂停动画
    pauseSimulation: () => {
      if (componentRef.current && componentRef.current.pauseSimulation) {
        componentRef.current.pauseSimulation();
      }
    },
    
    // 更新动画速度
    updateAnimationSpeed: (speed) => {
      if (componentRef.current && componentRef.current.updateAnimationSpeed) {
        componentRef.current.updateAnimationSpeed(speed);
      }
    },
    
    // 导出图片
    exportImage: () => {
      if (componentRef.current && componentRef.current.exportImage) {
        componentRef.current.exportImage();
      }
    },
    
    // 获取图实例
    getGraph: () => {
      if (componentRef.current && componentRef.current.getGraph) {
        return componentRef.current.getGraph();
      }
      return null;
    },

    // 获取当前插件信息
    getCurrentPlugin: () => currentPlugin,

    // 获取支持的图谱类型
    getSupportedGraphTypes: () => {
      if (!isPluginReady) return [];
      const registry = pluginInitializer.getRegistry();
      return registry.getRegisteredGraphTypes();
    },

    // 获取支持的布局类型
    getSupportedLayouts: (graphType) => {
      if (!isPluginReady) return [];
      const registry = pluginInitializer.getRegistry();
      return registry.getSupportedLayouts(graphType || 'knowledge');
    },

    // 检查兼容性
    isCompatible: (graphType, layout) => {
      if (!isPluginReady) return false;
      const registry = pluginInitializer.getRegistry();
      return registry.isCompatible(graphType, layout);
    }
  }));

  // 渲染加载状态
  if (!isPluginReady) {
    return (
      <div style={{
        width,
        height,
        display: 'flex',
        alignItems: 'center',
        justifyContent: 'center',
        border: '1px solid #d9d9d9',
        borderRadius: '8px',
        background: '#fafafa'
      }}>
        <div style={{ textAlign: 'center' }}>
          <div style={{ marginBottom: '8px' }}>正在初始化插件系统...</div>
          <div style={{ fontSize: '12px', color: '#666' }}>请稍候</div>
        </div>
      </div>
    );
  }

  // 渲染错误状态
  if (error) {
    return (
      <div style={{
        width,
        height,
        display: 'flex',
        alignItems: 'center',
        justifyContent: 'center',
        border: '1px solid #ff4d4f',
        borderRadius: '8px',
        background: '#fff2f0'
      }}>
        <div style={{ textAlign: 'center', color: '#ff4d4f' }}>
          <div style={{ marginBottom: '8px' }}>插件加载失败</div>
          <div style={{ fontSize: '12px' }}>{error.message}</div>
        </div>
      </div>
    );
  }

  // 渲染无插件状态
  if (!currentPlugin) {
    return (
      <div style={{
        width,
        height,
        display: 'flex',
        alignItems: 'center',
        justifyContent: 'center',
        border: '1px solid #faad14',
        borderRadius: '8px',
        background: '#fffbe6'
      }}>
        <div style={{ textAlign: 'center', color: '#faad14' }}>
          <div style={{ marginBottom: '8px' }}>未找到匹配的插件</div>
          <div style={{ fontSize: '12px' }}>图谱类型: {graphType}, 布局: {layout}</div>
        </div>
      </div>
    );
  }

  // 渲染插件组件
  try {
    const PluginComponent = currentPlugin.component;
    
    // 验证数据
    const graphPlugin = currentPlugin.graphPlugin;
    if (!graphPlugin.validateData(nodes, edges)) {
      throw new Error('数据格式不符合插件要求');
    }

    // 转换数据
    const transformedData = graphPlugin.dataTransformer(nodes, edges);
    
    // 获取布局配置
    const layoutConfig = currentPlugin.layoutPlugin.getLayoutConfig({
      nodeCount: nodes.length,
      edgeCount: edges.length
    });

    // 合并配置
    const mergedConfig = currentPlugin.config;

    const componentProps = {
      ref: componentRef,
      data: transformedData,
      layout: layoutConfig,
      width,
      height,
      onNodeClick,
      onEdgeClick,
      onNodePositionUpdate,
      editable,
      zoom,
      animationSpeed,
      isSimulationRunning,
      isFullscreen,
      onToggleFullscreen,
      graphType: currentPlugin.graphType,
      layoutType: currentPlugin.layout,
      config: mergedConfig,
      onReady: (apis) => {
        console.log('插件组件就绪:', currentPlugin.graphType, currentPlugin.layout);
        // 可以在这里添加额外的初始化逻辑
      }
    };

    return React.createElement(PluginComponent, componentProps);

  } catch (renderError) {
    console.error('插件组件渲染失败:', renderError);
    errorHandler(renderError);
    
    return (
      <div style={{
        width,
        height,
        display: 'flex',
        alignItems: 'center',
        justifyContent: 'center',
        border: '1px solid #ff4d4f',
        borderRadius: '8px',
        background: '#fff2f0'
      }}>
        <div style={{ textAlign: 'center', color: '#ff4d4f' }}>
          <div style={{ marginBottom: '8px' }}>组件渲染失败</div>
          <div style={{ fontSize: '12px' }}>{renderError.message}</div>
        </div>
      </div>
    );
  }
});

ModularGraphVisualizationHub.displayName = 'ModularGraphVisualizationHub';

export default ModularGraphVisualizationHub;